package com.supermap.dataservice.cloud.AgriStation;

import com.alibaba.dubbo.config.annotation.Service;
import com.supermap.dataservice.util.DateUtil;
import com.supermap.dataservice.util.EncodeUtils;
import com.supermap.dataservice.util.HttpRequest;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dubbo.api.AgriStation.ArgiStationService;
import com.supermap.dubbo.api.AgriStation.entity.AgriStationLiveData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static org.jsoup.nodes.Document.OutputSettings.Syntax.html;

/**
 * @Author:zhoujian
 * @Desciption:
 * @date:2019-04-03 10:40
 * @version:v1.0.0
 */
@Service
public class ArgiStationServiceImpl implements ArgiStationService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public JSONUtil getAgriStationLiveDataByDateRange(String url , String[] elements, String station , String nowDateTime , int length)
    {
        JSONUtil jsonUtil = new JSONUtil();
        try
        {
            AgriStationLiveData agriStationLiveData = new AgriStationLiveData();
            String[] timeSequence = new String[length];
            Map<String , float[]> elementAndValueMap = new HashMap<String , float[]>();
            //处理编码问题
            String encodeStationId = getEncodeStr(station);
            //处理要素编码问题
            String[] encodeElements = new String[elements.length];
            for(int i = 0 ; i< elements.length ; i ++)
            {
                String encodeElement = getEncodeStr(elements[i]);
                encodeElements[i] = encodeElement;
            }
            //处理时间，请求数据为当前时间与前length小时之间的逐小时数据
            //并且提供接口只能逐小时请求
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(DateUtil.StringToDate(nowDateTime , "yyyy-MM-dd HH:mm:ss"));
            //时间向前推移length小时
            calendar.add(Calendar.HOUR_OF_DAY,-1 * length);
            //循环时间取数据
            for (int j = 0 ; j < length ; j ++)
            {
                //数据开始时间
                String startDate = DateUtil.DateToString(calendar.getTime() , "yyyyMMddHH");
                //数据结束时间，向后推一小时
                calendar.add(Calendar.HOUR_OF_DAY,1);
                String endDate = DateUtil.DateToString(calendar.getTime() , "yyyyMMddHH");
                //拼装请求URL
                StringBuffer urlStr = new StringBuffer(url);
                urlStr.append("&stationstr=").append(encodeStationId).append(",")
                    .append("&begdate=").append(startDate)
                    .append("&enddate=").append(endDate)
                    .append("&fieldsstr=");
                for (String encodeElement : encodeElements)
                {
                    urlStr.append(encodeElement).append(",");
                }
                logger.info(String.format("请求路径：%s",urlStr.toString()));
               String result =  test1(urlStr.toString());//HttpRequest.httpURLConectionGET(urlStr.toString());
                //解析返回值
                if (result == null || "".equals(result))
               {
                    logger.info("获取农业观测站数据为空。");
               }else {
                     analysisResponse(result , j , length , agriStationLiveData , elementAndValueMap , timeSequence);
                }
            }
        agriStationLiveData.setElementAndValueMap(elementAndValueMap);
        agriStationLiveData.setTimeSequence(timeSequence);
        jsonUtil.setData(agriStationLiveData);
        }catch (Exception ex)
        {
            logger.error("请求农业气象站观测数据异常，异常信息为：" + ex);
            jsonUtil.setMsg("请求农业气象站观测数据后端异常。");
            jsonUtil.setCode(100);
            jsonUtil.setIsSuccess(false);
        }
        return  jsonUtil;
    }
    public static String test1(String uri) {
        String resultStr = null;
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("GET"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();

//            System.out.println(result.toString());
            resultStr = result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }
    private void analysisResponse(String result , int index , int length ,AgriStationLiveData agriStationLiveData ,
                                                 Map<String , float[]> elementAndValueMap,String[] timeSequence) throws  Exception
    {
        try {
            //解析返回的结果,返回的结果为html格式
            Document doc = Jsoup.parse(result);
            Elements rows = doc.select("table[class=tr_zdyb]").get(0).select("tr");
            if (rows.size() == 1){
                logger.info("请求返回没有结果");
            }else if (rows.size() == 2){
                logger.info("请求返回只有标题信息没有数据");
            }
            else{
                for (int k = 2 ; k < rows.size() ; k ++)
                {
                    Element row = rows.get(k);
                    if (!row.hasText())
                    {
                        System.out.println("没有内容");
                        continue;
                    }
                    String stationId1 = row.select("td").get(0).text().trim();
                    agriStationLiveData.setStationId(stationId1);
                    String dateTime = row.select("td").get(1).text().trim();
                    timeSequence[index] = DateUtil.StringToString(dateTime, "yyyyMMddHHmmss", "yyyyMMddHH");
                    String elementName = elementChange(row.select("td").get(2).text().trim());

                    String elementValue = row.select("td").get(3).text().equals("/") == true ? null : row.select("td").get(3).text();
                    if (elementAndValueMap.containsKey(elementName))
                    {
                        if (elementValue != null)
                        {
                            if ("第一层气温".equals(elementName))
                            {
                                elementAndValueMap.get(elementName)[index] = (float)(Float.parseFloat(elementValue) / 10.0);
                            }else
                            {
                                elementAndValueMap.get(elementName)[index] = Float.parseFloat(elementValue);
                            }
                        }
                    }else {
                        //不存在
                        float[] values = null;
                        if (elementValue != null)
                        {
                            values = new float[length];
                            if ("第一层气温".equals(elementName))
                            {
                                //对气温除以10
                                values = new float[length] ;
                                values[index] = (float)(Float.parseFloat(elementValue ) / 10.0);
                            }else{
                                values = new float[length];
                                values[index] = Float.parseFloat(elementValue);
                            }
                        }
                        elementAndValueMap.put(elementName, values);
                    }
                    System.out.print(row.select("td").get(0).text()+"  ");
                    System.out.print(row.select("td").get(1).text()+"  ");
                    System.out.print(row.select("td").get(2).text()+"  ");
                    System.out.print(row.select("td").get(3).text()+"  ");
                    System.out.println();
                }
            }
        }catch (Exception ex)
        {
            logger.error("解析农业气象观测站返回结果异常，异常信息为：" + ex);
            throw  new Exception("解析农业气象观测站返回结果异常，异常信息为：" + ex);
        }
    }

    /**
     * 要素转换
     * @param element
     * @return
     */
    private String elementChange(String element) {
        switch (element){
            case "小时降水":
                return  "PRE";
            case "第一层气温":
                return  "TMP";
            case "第一层湿度":
                return  "HUM";
            case "光合有效辐射曝辐量":
                return  "HIV";
                default:
                    return element;
        }
    }

    /**
     * 转码成gb2312
     * @param str 转码字符串【格式为：str1_str2 或者 str1】
     * @return
     * @throws Exception
     */
    private String getEncodeStr(String str) throws  Exception{
        String[] array = str.split("_");
        String encodeStr = array.length == 2 ? EncodeUtils.gb2312eecode(array[0])+"_"+array[1]: array.length==1?EncodeUtils.gb2312eecode(array[0]):"";
        return  encodeStr;
    }

}